package com.bw.kylin1705f.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bw.kylin1705f.dto.RoleDTO;
import com.bw.kylin1705f.dto.UserRoleDTO;
import com.bw.kylin1705f.entity.Role;
import com.bw.kylin1705f.entity.UserRole;
import com.bw.kylin1705f.service.IRoleService;
import com.bw.kylin1705f.service.IUserRoleService;
import com.bw.kylin1705f.vo.ResultEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mht
 * @since 2019-12-05
 */
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController {

    @Autowired
    IRoleService roleService;

    @Autowired
    IUserRoleService userRoleService;

    @RequestMapping("/list")
    public ResultEntity getRoleList(RoleDTO roleDTO){
        Wrapper<Role> wrapper = new EntityWrapper<Role>();
        PageHelper.startPage(roleDTO.getPageNo(),roleDTO.getPageSize());
        List<Role> roleList = roleService.selectList(wrapper);
        PageInfo pageInfo = new PageInfo(roleList);
        return ResultEntity.ok(pageInfo);
    }

    @RequestMapping("/all")
    public ResultEntity getRoleAll(){
        Wrapper<Role> wrapper = new EntityWrapper<Role>();
        List<Role> roleList = roleService.selectList(wrapper);
        return ResultEntity.ok(roleList);
    }

    @RequestMapping("/getRoleListByUid")
    public ResultEntity getRoleListByUid(int uid){
        Wrapper<UserRole> wrapper = new EntityWrapper();
        wrapper.eq("uid",uid);
        List<UserRole> roles = this.userRoleService.selectList(wrapper);
        return ResultEntity.ok(roles);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResultEntity  saveUserRole(@RequestBody  UserRoleDTO userRoleDTO){

        log.info("入参为{}", JSON.toJSONString(userRoleDTO));
        List<UserRole> roles = new ArrayList<>();
        for (int rid:userRoleDTO.getRoleList()){
            UserRole userRole = new UserRole();
            userRole.setUid(userRoleDTO.getUid());
            userRole.setRid(rid);
            roles.add(userRole);
        }
        userRoleService.add(roles);
        return ResultEntity.ok("成功");
    }




}
